#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "mt_random.h"

double random1(){
	return rand()/(double)RAND_MAX;
}

double random2(){
	double r=0.0;
	double s=1.0/(double)RAND_MAX;
	double p=1.0;
	int i;
	for(i=0;i<16;i++){
		r+=rand()*s*p;
		p*=.1;
	}
	return r;
}

double random3(){
	return mt_random()/(double)0xFFFFFFFF;
}

int randint(int a){
	return rand()%a;
}
int randint3(int a){
	return mt_random()%a;
}

void get_unique_filename(const char* filename,char* unique_filename) {
	int n,m,flag;
	FILE* f;
	char ext[50];
	char blunt[100];
	char num[5];
	n=0;
	flag=0;
	m=0;
	while(filename[n]){
		if (filename[n]=='.') {
			flag=1;
			blunt[n]=0;
		}
		if (flag) ext[m++]=filename[n];
		else blunt[n]=filename[n];
		n++;
	}
	ext[m]=0;
	if(!flag) blunt[n]=0;
	n=0;
	while(1) {
		n++;
		strcpy(unique_filename,blunt);
		sprintf(num,".%03d",n);
		strcat(unique_filename,num);
		if(m) strcat(unique_filename,ext);
		if(!fopen(unique_filename,"r")) break;
	}
}

double dfloor(double a){
	if (a<0) return ceil(a);
	return floor(a);
}
double dround(double a, int ndigits){
	double r;
	double p=pow(10,ndigits);
	a*=p;
	if(a<0){
		r=ceil(a);
		if((r-a)>0.5) r--;
	} else {
		r=floor(a);
		if((a-r)>0.5) r++;
	}
	r/=p;
	return r;

}

double dtrunc(double a, int ndigits){
	double p=pow(10,ndigits);
	a*=p;
	a=dfloor(a);
	a/=p;
	return a;
}

int round2int(double a){
	int r;
	r=(int)a;
	if ((a-r)>0.5) return r+1;
	return r;
}
